package com.gombe.credit.app.ui.adapter

import android.annotation.SuppressLint
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gombe.credit.app.R
import com.gombe.credit.app.configs.GombeCreditConfigs
import com.gombe.credit.app.event.GombeCreditEventPointHelper
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.decoration.GridSpacingItemDecoration
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedKey
import com.gombe.credit.app.weight.font.LexendMediumEditText
import com.gombe.credit.lib.adapter.GombeCreditRecyclerViewAdapter
import com.gombe.credit.lib.adapter.GombeCreditViewHolderHelper
import org.json.JSONObject

/**
GombeCredit * @Author wwdeng
 * @CreateTime: 2024/11/19 13:54
 * @Annotation：认证流程步骤适配器
 */
class AdapterGombeCreditStepGeneral(recyclerView: RecyclerView?): GombeCreditRecyclerViewAdapter<JSONObject>(recyclerView) {
    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "GENDER_PICK" -> {//性别
                return R.layout.fragment_gombe_credit_step_general_gender_item
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                return R.layout.fragment_gombe_credit_step_contact_relation_item
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.fragment_gombe_credit_step_contact_mobile_item
            }
            "DATE_PICK",
            "SELECT" -> {//出生日期选择,选择
                return R.layout.fragment_gombe_credit_step_general_select_item
            }
            else -> {//输入框
                return R.layout.fragment_gombe_credit_step_general_input_item
            }
        }
    }

    override fun setItemChildListener(helper: GombeCreditViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.authStepSelect)//选择
        helper.setItemChildClickListener(R.id.authStepContactImage)//选择联系人
        helper.setItemChildClickListener(R.id.authStepMobile)
    }

    override fun fillData(helper: GombeCreditViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val authStepTitle = helper.getTextView(R.id.authStepTitle)
        var showTitle = model.optString("title")
        if (GombeCreditConfigs.isGombeCreditSwahili()){
            showTitle = model.optString("title_sw")
        }
        authStepTitle.text = findKeywordColor(getColor(R.color.gombe_credit_FFFF4D3E),showTitle,"*")

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT" ->{//生日选择,选择
                showAuthStepSelectItemView(helper,position,model)
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                showAuthStepContactRelationItemView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showAuthStepContactMobileItemView(helper,position,model)
            }
            "GENDER_PICK" -> {//性别
                showAuthStepGenderItemView(helper,position,model)
            }
            else -> {//输入框
                showAuthStepInputItemView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showAuthStepInputItemView(helper: GombeCreditViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val authStepEdit = helper.getView<LexendMediumEditText>(R.id.authStepEdit)
        var showHint = model.optString("hint")
        if (GombeCreditConfigs.isGombeCreditSwahili()){
            showHint = model.optString("hint_sw")
        }
        authStepEdit.setHint(showHint)
        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            if (selectItem != null) {
                showText = selectItem.optString("title")
            }
        }
        authStepEdit.setText(showText)
        authStepEdit.setInputFocusChangeListener(object : LexendMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
//                if (hasFocus){
//                    authStepEdit.shapeDrawableBuilder
//                        .setStrokeColor(getColor(R.color.color_ff0569ff))
//                        .intoBackground()
//                } else {
//                    authStepEdit.shapeDrawableBuilder
//                        .setStrokeColor(getColor(R.color.color_ffeceff3))
//                        .intoBackground()
//                }
            }
            override fun onCompleteAction(v: View?, remark: String) {
                var eventType = String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                GombeCreditEventPointHelper.addEventPointRequestAction(eventType,remark)
            }
        })

        authStepEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepEdit.clearFocus()
                true
            }
            false
        }
        authStepEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 生日选择,选择
     */
    private fun showAuthStepSelectItemView(helper: GombeCreditViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (GombeCreditConfigs.isGombeCreditSwahili()){
            showHint = model.optString("hint_sw")
        }
        val authStepSelectText = helper.getTextView(R.id.authStepSelectText)
        authStepSelectText.setHint(showHint)
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            var showTitle = selectItem.optString("title")
            if (GombeCreditConfigs.isGombeCreditSwahili()){
                showTitle = selectItem.optString("title_sw")
            }
            authStepSelectText.text = showTitle
        }

        val authStepSelectImage = helper.getImageView(R.id.authStepSelectImage)
        if (model.optString("action") == "DATE_PICK"){
            authStepSelectImage.setImageResource(R.mipmap.gombe_credit_image_birthdate_icon)
        } else {
            authStepSelectImage.setImageResource(R.mipmap.gombe_credit_image_down_black_icon)

        }
    }

    /**
     * 性别选择
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun showAuthStepGenderItemView(helper: GombeCreditViewHolderHelper, position: Int, model: JSONObject){
        val recyclerView = helper.getView<RecyclerView>(R.id.recyclerViewChild)
        val layoutManager = GridLayoutManager(mContext,2)
        recyclerView.layoutManager = layoutManager
        if (recyclerView.itemDecorationCount == 0){
            val endDecoration = GombeCreditDensityUtil.dp2px(16f)
            recyclerView.addItemDecoration(GridSpacingItemDecoration(2, endDecoration, false))
        }
        val genderItemAdapter = AdapterGombeCreditStepGenderItem(recyclerView)
        recyclerView.adapter = genderItemAdapter
        recyclerView.itemAnimator = DefaultItemAnimator()
        genderItemAdapter.setOnItemChildClickListener{ _, childView, position ->
            val item = genderItemAdapter.getItem(position)
            if (item.optBoolean("isSelected",false)){
                return@setOnItemChildClickListener
            }
            genderItemAdapter.data.forEach {
                it.put("isSelected",false)
            }
            item.put("isSelected",true)
            model.put("selectItem",item)
            genderItemAdapter.notifyDataSetChanged()

            val subRemark = item.optString("value")
            GombeCreditEventPointHelper.addEventPointRequestAction(String.format(
                GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_XX_SELECT,model.optString("paramName")),subRemark)
        }
        val childList = arrayListOf<JSONObject>()
        val dataArray = model.optJSONArray("values")
        if (dataArray != null) {
            for (i in 0..<dataArray.length()) {
                val genderItem = dataArray.optJSONObject(i)
                childList.add(genderItem)
            }
        }
        genderItemAdapter.data = childList
    }

    /**
     * 联系人关系
     */
    private fun showAuthStepContactRelationItemView(helper: GombeCreditViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (GombeCreditConfigs.isGombeCreditSwahili()){
            showHint = model.optString("hint_sw")
        }
        //选择关系
        val authStepSelectText = helper.getTextView(R.id.authStepSelectText)
        authStepSelectText.setHint(showHint)
        //输入关系
        val authStepEdit = helper.getView<LexendMediumEditText>(R.id.authStepEdit)
        //todo 此处确实选择Other时输入框的提示
        authStepEdit.setHint(model.optString("relationOtherHint"))
        authStepEdit.visibility = View.GONE

        var showTitle = ""
        var showOtherValue = ""
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            showTitle = selectItem.optString("title")
            if (GombeCreditConfigs.isGombeCreditSwahili()){
                showTitle = selectItem.optString("title_sw")
            }
            if (showTitle == model.optString("relationOtherKey")){
                authStepEdit.visibility = View.VISIBLE
                if (selectItem.has("otherValue")){
                    showOtherValue = selectItem.optString("otherValue","")
                }
            }
        }
        authStepSelectText.text = showTitle

        //关系为“Other”时，输入框允许输入
        authStepEdit.isEnabled = showTitle == model.optString("relationOtherKey")
        authStepEdit.setText(showOtherValue)
        authStepEdit.setInputFocusChangeListener(object : LexendMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
//                if (hasFocus){
//                    authStepEdit.shapeDrawableBuilder
//                        .setStrokeColor(getColor(R.color.color_ff0569ff))
//                        .intoBackground()
//                } else {
//                    authStepEdit.shapeDrawableBuilder
//                        .setStrokeColor(getColor(R.color.color_ffeceff3))
//                        .intoBackground()
//                }
            }
            override fun onCompleteAction(v: View?, remark: String) {
                var eventType = String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                GombeCreditEventPointHelper.addEventPointRequestAction(eventType,remark)
            }
        })
        authStepEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepEdit.clearFocus()
                true
            }
            false
        }

        authStepEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                if (model.has("selectItem")){
                    val selectItem = model.getJSONObject("selectItem")
                    selectItem.put("otherValue",s.toString())
                }
            }
        })
    }

    /**
     * 联系电话
     */
    private fun showAuthStepContactMobileItemView(helper: GombeCreditViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (GombeCreditConfigs.isGombeCreditSwahili()){
            showHint = model.optString("hint_sw")
        }
        val authStepMobile = helper.getTextView(R.id.authStepMobile)
        authStepMobile.setHint(showHint)
        val authStepMobileEdit = helper.getView<LexendMediumEditText>(R.id.authStepMobileEdit)
        authStepMobileEdit.setHint(showHint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            authStepMobile.text = showValue
            authStepMobileEdit.setText(showValue)
        }
        authStepMobileEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepMobileEdit.clearFocus()
                true
            }
            false
        }
        authStepMobileEdit.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus){
                GombeCreditEventPointHelper.addEventPointRequestAction(String.format(
                    GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.STEP_INPUT_XX,model.optString("paramName")),authStepMobileEdit.text.toString())
            }
        }
        authStepMobileEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //是否是审核账号
        val isAdmin = GombeCreditSharedHelper.takeGombeCreditSharedBoolean(GombeCreditSharedKey.GOMBECREDIT_IS_CONFIG_ACCOUNT)
        if(isAdmin){//审核账号 - 允许输入或选择
            authStepMobile.visibility = View.GONE
            authStepMobileEdit.visibility = View.VISIBLE
        } else {//非审核账号只能选择
            //设备是否支持通讯录选择联系人
            if (model.optBoolean("isContactPick")){
                authStepMobile.visibility = View.VISIBLE
                authStepMobileEdit.visibility = View.GONE
            } else {
                authStepMobile.visibility = View.GONE
                authStepMobileEdit.visibility = View.VISIBLE
            }
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}